package com.huaxonline.boot.file;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.InputStream;

/**
 * @author Administrator
 */
@Slf4j
public abstract class AbstractFileStorageService implements IFileStorageService {

    @Override
    public boolean upload(String localFile, String remoteFile) {
        if (!StringUtils.hasText(localFile) || !StringUtils.hasText(remoteFile)) {
            log.error("文件路径不能为空");
            return false;
        }

        if (!localFile.contains(".")) {
            throw new IllegalArgumentException("本地文件缺少后缀名");
        }

        try {
            return doUpload(localFile, remoteFile);
        } catch (Exception e) {
            log.error("文件上传失败: {}", e.getMessage(), e);
            return false;
        }
    }

    @Override
    public boolean upload(InputStream in, String remoteFile) {
        if (in == null || !StringUtils.hasText(remoteFile)) {
            log.error("输入流或远程文件路径不能为空");
            return false;
        }

        try {
            return doUpload(in, remoteFile);
        } catch (Exception e) {
            log.error("文件上传失败: {}", e.getMessage(), e);
            return false;
        }
    }

    @Override
    public boolean download(String remoteFile, String localFile) {
        if (!StringUtils.hasText(remoteFile) || !StringUtils.hasText(localFile)) {
            log.error("文件路径不能为空");
            return false;
        }

        try {
            return doDownload(remoteFile, localFile);
        } catch (Exception e) {
            log.error("文件下载失败: {}", e.getMessage(), e);
            return false;
        }
    }

    @Override
    public boolean delete(String remoteFile) {
        if (!StringUtils.hasText(remoteFile)) {
            log.error("文件路径不能为空");
            return false;
        }

        try {
            return doDelete(remoteFile);
        } catch (Exception e) {
            log.error("文件删除失败: {}", e.getMessage(), e);
            return false;
        }
    }

    @Override
    public boolean exists(String remoteFile) {
        if (!StringUtils.hasText(remoteFile)) {
            log.error("文件路径不能为空");
            return false;
        }

        try {
            return doExists(remoteFile);
        } catch (Exception e) {
            log.error("检查文件存在性失败: {}", e.getMessage(), e);
            return false;
        }
    }

    // 抽象方法，由具体实现类实现
    protected abstract boolean doUpload(String localFile, String remoteFile) throws Exception;

    protected abstract boolean doUpload(InputStream in, String remoteFile) throws Exception;

    protected abstract boolean doDownload(String remoteFile, String localFile) throws Exception;

    protected abstract boolean doDelete(String remoteFile) throws Exception;

    protected abstract boolean doExists(String remoteFile) throws Exception;
}